package com.eason.controller;

import com.eason.pojo.Books;
import com.eason.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller 调用 service层
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    //查询全部书籍并返回页面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.selectAllBooks();
        model.addAttribute("list",list);

        return "allBook";
    }

    //跳转新增书籍页面
    @RequestMapping("/toAddPage")
    public String toAddPage(){
        return "addBook";
    }
    //添加书籍请求
    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook=>" + books);
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向
    }

    //跳转修改书籍页面
    @RequestMapping("/updatePage")
    public String updatePage(int id,Model model){
        Books books = bookService.selectBookById(id);
        model.addAttribute("selectebook",books);
        return "updateBook";
    }
    //修改书籍请求
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        System.out.println("修改成功！");
        return "redirect:/book/allBook";
    }

    //删除书籍请求
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteById(id);
        System.out.println("删除成功！");
        return "redirect:/book/allBook";
    }

    //查询书籍功能
    @RequestMapping("/seleteBook")
    public String seleteBookName(String selectBookName,Model model){
        Books book = bookService.seleteBookByName(selectBookName);

        List<Books> list = new ArrayList<>();
        list.add(book);
        model.addAttribute("list",list);
        return "allBook";
    }
}
